import React from 'react'
import {connect} from 'react-redux'
import menuRoute from 'routes/menuRoute'
import SlideFrame from 'components/slide-frame'
import SearchArea from 'components/search-area'
import backlashService from './pay-backlash-recheck.service'
import moment from 'moment'
import { Table, Popover } from 'antd'
import toBacklash from './to-backlash-rechecked';
import {messages, queryCurrencyPrecision} from 'share/common'

class BacklashRechecked extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      visible: false,
      setOfBooksId: null,
      searchForm: [
        {type: 'input', id: 'billCode', label: messages('pay.key181')/*反冲付款流水号*/},
        {type: 'input', id: 'refBillCode', label: messages('pay.key182')/*原付款流水号*/},
        {
          type: 'items', id: 'dateRange', items: [
            {
              type: 'date',
              id: 'backFlashDateFrom',
              label: messages('pay.key183')/*反冲日期从*/
            },
            {type: 'date', id: 'backFlashDateTo', label: messages('pay.key184')/*反冲日期到*/}
          ]
        },
        {
          type: 'items', id: 'amountRange', items: [
            {type: 'inputNumber', id: 'amountFrom', label: messages('pay.key185')/*反冲金额从*/},
            {type: 'inputNumber', id: 'amountTo', label: messages('pay.key186')/*反冲金额到*/}
          ]
        }
      ],
      canBacklashSearchParams: {},
      columns: [
        {
          title: messages('pay.key181')/*反冲付款流水号*/, dataIndex: 'billcode', width: 250, align: "center",
          render: desc => <span><Popover content={desc}>{desc ? desc : "-"}</Popover></span>
        },
        {
          title: messages('pay.key182')/*原付款流水号*/,
          dataIndex: 'refBillCode',
          width: 250,
          align: "center",
          render: desc => <span><Popover content={desc}>{desc ? desc : "-"}</Popover></span>
        },
        {
          title: messages('pay.key188')/*反冲日期*/, dataIndex: 'refundDate', width: 150, align: "center",
          render: desc => <span><Popover
            content={moment(desc).format('YYYY-MM-DD')}>{desc ? moment(desc).format('YYYY-MM-DD') : "-"}</Popover></span>
        },
        {
          title: messages('pay.key209')/*提交人*/, dataIndex: 'createdByName', width: 150, align: "center",
          render: desc => <span><Popover content={desc}>{desc ? desc : "-"}</Popover></span>
        },

        {title: messages('pay.key82')/*币种*/, dataIndex: 'currency', align: "center", width: 150},
        {
          title: messages('pay.key189')/*反冲金额*/, dataIndex: 'amount', width: 150, align: "center",
          render: (desc, record) => <span><Popover
            content={this.filterMoney(desc, queryCurrencyPrecision(record.currency), true)}>{this.filterMoney(desc, queryCurrencyPrecision(record.currency), true)}</Popover></span>
        },
        {
          title: messages('common.remark')/*备注*/, dataIndex: 'remark', align: "center",
          render: desc => <span><Popover content={desc}>{desc ? desc : "-"}</Popover></span>
        }
      ],
      data: [],
      canBacklashPage: 0,
      canBacklashPageSize: 10,
      searchParams: {},
      canBacklashPagination: {
        total: 0
      },
      canBacklashData: [],
      goBacklash: null,
      openWindowFlag: false,//发起反冲窗口
      NewPayRequisition: menuRoute.getRouteItem('new-pre-payment', 'key'), //新建预付款
      PayRequisitionDetail: menuRoute.getRouteItem('pre-payment-detail', 'key'), //预付款详情,
      ContractDetail: menuRoute.getRouteItem('contract-detail', 'key'), //合同详情
      toBacklash: menuRoute.getRouteItem('to-backlash', 'key')    //发起反冲页面
    }
  }

  //反冲窗口关闭
  cancelWindow = () => {
    this.setState({openWindowFlag: false});
  };

  //反冲窗口完全关闭后回掉
  restFormFunc = () => {
    this.setState({openWindowFlag: false}, () => {
      this.getCanBacklashList();
    });
  };

  //可反冲列表搜索
  canBacklashHandle = (values) => {
    values.backFlashDateFrom && (values.backFlashDateFrom = values.backFlashDateFrom.format('YYYY-MM-DD'));
    values.backFlashDateTo && (values.backFlashDateTo = values.backFlashDateTo.format('YYYY-MM-DD'));
    this.setState({canBacklashSearchParams: values, canBacklashPage: 0}, () => {
      this.getCanBacklashList()
    })
  };

  componentWillMount() {
    this.getCanBacklashList(this.state.nowStatus);
  }

  //可反冲点击页码
  canBacklashChangePaper = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({canBacklashPage: page - 1}, () => {
        this.getCanBacklashList()
      })
    }
  };

  //获取可反冲列表
  getCanBacklashList = (resolve, reject) => {
    const {canBacklashPage, canBacklashPageSize, canBacklashSearchParams} = this.state;
    this.setState({loading1: true});
    let params = {...canBacklashSearchParams, page: canBacklashPage, size: canBacklashPageSize, status: "S"};
    backlashService.getBacklashRecheck(params).then((res) => {
      if (res.status === 200) {
        this.setState({
          canBacklashData: res.data || [],
          loading1: false,
          canBacklashPagination: {
            total: Number(res.headers['x-total-count']) ? Number(res.headers['x-total-count']) : 0,
            current: canBacklashPage + 1,
            onChange: this.canBacklashChangePaper,
            pageSize: canBacklashPageSize,
            pageSizeOptions: ['10', '20', '30', '40'],
            showSizeChanger: true,
            onShowSizeChange: this.onChangePageSize,
            showQuickJumper: true,
            showTotal: (total, range) => {messages('pay.key175',{arg1:range[0],arg2:range[1],arg3:total})/*显示 {arg1}-{arg2} 共 {arg3} 条*/}
          }
        });
        resolve && resolve()
      }
    }).catch(() => {
      this.setState({loading1: false});
      reject && reject()
    })
  };

  //每页多少条
  onChangePageSize = (page, pageSize) => {
    if (page - 1 !== this.state.canBacklashPage || pageSize !== this.state.canBacklashPageSize) {
      this.setState({canBacklashPage: page - 1, canBacklashPageSize: pageSize}, () => {
        this.getCanBacklashList();
      })
    }
  };

  //点击行去复核页面
  rowClick(record) {
    //根据支付明细id查询详情，再将record传过去
    backlashService.getBacklashDTOBybacklashDetailId(record.id).then(
      res => {
        if (res.status === 200) {
          this.setState({openWindowFlag: true, goBacklash: res.data});
        }
      }
    )
  }

  render() {
    const {goBacklash, openWindowFlag, loading1, searchForm, columns, canBacklashData, canBacklashPagination} = this.state;
    return (
      <div className="pay-my-backlash">
        <SearchArea searchForm={searchForm}
                    submitHandle={this.canBacklashHandle}
                    clearHandle={() => {
                    }}
                    maxLength={4}
                    eventHandle={this.eventHandle}
                    wrappedComponentRef={(inst) => this.formRef = inst}/>
        <div className="table-header"/>
        <Table rowKey={record => record.id}
               columns={columns}
               dataSource={canBacklashData}
               pagination={canBacklashPagination}
               loading={loading1}
               onRow={record => ({
                 onClick: () => this.rowClick(record)
               })}
               bordered
               size="middle"/>
        <SlideFrame title={messages('pay.key176')/*反冲信息详情*/}
                    show={openWindowFlag}
                    content={toBacklash}
                    params={{record: goBacklash, flag: openWindowFlag}}
                    onClose={this.cancelWindow}
                    afterClose={this.restFormFunc}/>
      </div>
    );
  }
}

BacklashRechecked.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company
  }
}

export default connect(mapStateToProps, null, null, {withRef: true})(BacklashRechecked);


